package com.tanger.auth.provider;

import com.tanger.auth.mapper.AuthMapper;
import com.tanger.common.redis.RedisUtil;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 第三方登录(微信)
 */
public class SocialTokenGranter extends AbstractTokenGranter {
   private final AuthMapper authMapper;
   private final RedisUtil redisUtils;

   public SocialTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                             OAuth2RequestFactory requestFactory, AuthMapper authMapper, RedisUtil redisUtils) {
      this(tokenServices, clientDetailsService, requestFactory, authMapper, redisUtils, "social");
   }

   protected SocialTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                                OAuth2RequestFactory requestFactory, AuthMapper authMapper, RedisUtil redisUtils, String grantType) {
      super(tokenServices, clientDetailsService, requestFactory, grantType);
      this.authMapper = authMapper;
      this.redisUtils = redisUtils;
   }

   protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
      Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
      System.out.println("第三授权"+ client.getClientId()+" "+client.getScope());
      String code = parameters.get("code");
      String openId = parameters.get("openId");
      String roletype = (String)parameters.get("roletype");
      Authentication userAuth = null;

      try {
//         LinkedHashMap<String, String> user = authMapper.getSysUserByMobile(mobile);
//
//         if (user == null) {
//            throw new UsernameNotFoundException(String.format("找不到此手机号%s。", mobile));
//         }
//         if (StringUtil.isNull(openId)) {
//            String result = OAuthServiceImp.getSessionKeyBycode(code);
//            JSONObject res = JSONObject.parseObject(result);
//            if (!res.containsKey("openid")) {
//               throw new RuntimeException("微信授权失败");
//            }
//            openId = res.getString("openid");
//         }
//
//         List<String> roleCodeList = this.authMapper.queryRoleCodeByMobile(mobile);
//         UserDetails userDetails = new User((String)user.get("USERNAME"), (String)user.get("PASSWORD"), AuthorityUtils.createAuthorityList((String[])roleCodeList.toArray(new String[0])));
//         userAuth = new UsernamePasswordAuthenticationToken(userDetails, (Object)null, userDetails.getAuthorities());
//         ((AbstractAuthenticationToken)userAuth).setDetails(parameters);
      } catch (AccountStatusException var10) {
         throw new InvalidGrantException(var10.toString());
      } catch (BadCredentialsException var11) {
         throw new InvalidGrantException(var11.toString());
      }

      if (!userAuth.isAuthenticated()) {
         throw new InvalidGrantException("Could not authenticate mobile: " + openId);
      } else {
         OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
         return new OAuth2Authentication(storedOAuth2Request, userAuth);
      }
   }
}
